<script setup lang="ts">
import type {
  OnActionClickParams,
  VxeTableGridOptions,
} from '#/adapter/vxe-table';
import type { CompanyApi } from '#/api/system/company';
import type { DepartmentApi } from '#/api/system/department';

import { ref } from 'vue';

import { Page, useVbenDrawer } from '@vben/common-ui';
import { Plus } from '@vben/icons';

import { ElButton, ElMessage, ElMessageBox } from 'element-plus';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { deleteCompany, getCompanyList } from '#/api/system/company';
import { EditInfo } from '#/components/edit-info/index';
import { $t } from '#/locales';
import DepartmentForm from '#/views/system/company/components/departmentForm.vue';
import {
  useCompanyGridColumns,
  useCompanyGridFormSchema,
} from '#/views/system/company/data';

import CompanyDepartmentList from './components/CompanyDepartmentList.vue';
import CompanyForm from './components/companyForm.vue';

/** 刷新表格 */
function onCompanyRefresh() {
  companyGridApi.query();
}

function onCompanyEdit(row: CompanyApi.Company) {
  companyFormDrawerApi.setData(row).open();
}

function onCompanyCreate() {
  companyFormDrawerApi.setData(null).open();
}

/** 删除角色 */
async function onCompanyDelete(row: CompanyApi.Company) {
  await ElMessageBox.confirm('确定要删除该公司吗？', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  });
  await deleteCompany(row.id as number);
  ElMessage.success($t('ui.actionMessage.deleteSuccess', [row.name]));
  onCompanyRefresh();
}

const [CompanyFormDrawer, companyFormDrawerApi] = useVbenDrawer({
  connectedComponent: CompanyForm,
  destroyOnClose: true,
});

function onCompanyActionClick({
  code,
  row,
}: OnActionClickParams<CompanyApi.Company>) {
  switch (code) {
    case 'add-department': {
      onDepartmentCreate(row.id!);
      break;
    }
    case 'delete': {
      onCompanyDelete(row);
      break;
    }
    case 'edit': {
      onCompanyEdit(row);
      break;
    }
  }
}

const [CompanyGrid, companyGridApi] = useVbenVxeGrid({
  formOptions: {
    schema: useCompanyGridFormSchema(),
  },
  gridOptions: {
    columns: useCompanyGridColumns(onCompanyActionClick),
    height: 'auto',
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          return await getCompanyList({
            pageNum: page.currentPage,
            pageSize: page.pageSize,
            ...formValues,
          });
        },
      },
    },
    expandConfig: {
      accordion: true,
    },
  } as VxeTableGridOptions<CompanyApi.Company>,
});

function onDepartmentEdit(row: DepartmentApi.Department) {
  departmentFormDrawerApi.setData(row).open();
}

// 存储当前活跃的部门列表组件实例的 Map
const activeDepartmentLists = ref(new Map<number, any>());

function onDepartmentCreate(companyId: number) {
  departmentFormDrawerApi.setData({ companyId }).open();
}

/** 刷新部门表格 */
function onDepartmentRefresh() {
  // 刷新所有当前活跃的部门列表组件
  activeDepartmentLists.value.forEach((componentInstance) => {
    if (componentInstance && componentInstance.refresh) {
      componentInstance.refresh();
    }
  });
}

// 注册部门列表组件实例
function registerDepartmentList(companyId: number, componentInstance: any) {
  activeDepartmentLists.value.set(companyId, componentInstance);
}

const [DepartmentFormDrawer, departmentFormDrawerApi] = useVbenDrawer({
  connectedComponent: DepartmentForm,
  destroyOnClose: true,
});
</script>

<template>
  <Page auto-content-height>
    <CompanyFormDrawer @success="onCompanyRefresh" />
    <DepartmentFormDrawer @success="onDepartmentRefresh" />
    <CompanyGrid table-title="公司列表">
      <template #edit-info="{ row }">
        <EditInfo :handler-name="row.handlerName" :time="row.updateTime" />
      </template>
      <template #expand-content="{ row }">
        <CompanyDepartmentList
          :ref="(el) => el && registerDepartmentList(row.id!, el)"
          :company-id="row.id!"
          @edit-department="onDepartmentEdit"
          @delete-department="() => {}"
        />
      </template>
      <template #toolbar-tools>
        <ElButton
          type="primary"
          @click="onCompanyCreate"
          v-access:code="['system:company:add']"
        >
          <Plus class="mr-2 size-5" />
          {{ $t('ui.company.create') }}
        </ElButton>
      </template>
    </CompanyGrid>
  </Page>
</template>
